package com.sx.pipeline.ui.workbench

import android.content.Context
import android.view.View
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.tabs.TabLayoutMediator
import com.gyf.immersionbar.ImmersionBar
import com.hjq.widget.utils.DisplayUtil
import com.hjq.widget.view.rolling.RollingTextAdapter
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.adapter.HomeApplyAdapter
import com.sx.pipeline.adapter.HomeBannerAdapter
import com.sx.pipeline.adapter.ProvideListAdapter
import com.sx.pipeline.adapter.SupplierNeedsListAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseFragment
import com.sx.pipeline.app.config.CommonApplyType
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.app.config.NewsQuantityType
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.FragWorkbenchBinding
import com.sx.pipeline.databinding.ViewItemRollingBinding
import com.sx.pipeline.repos.http.res.BannerVO
import com.sx.pipeline.repos.http.res.CommonApplyListVO
import com.sx.pipeline.repos.http.res.ReleaseNeedsVO
import com.sx.pipeline.repos.http.res.ReleaseSupplyVo
import com.sx.pipeline.ui.Main2Activity
import com.sx.pipeline.ui.workbench.adapter.TaskPageAdapter

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Desc: 工作台
 */
class WorkBenchFragment : CYDataBindingBaseFragment<FragWorkbenchBinding, WorkBenchVM>
    (R.layout.frag_workbench), View.OnClickListener, OnRefreshLoadMoreListener {

    // 轮播图
    private lateinit var mBannerAdapter: HomeBannerAdapter

    // 常用应用适配器
    private lateinit var mHomeApplyAdapter: HomeApplyAdapter

    // 任务页面
    private lateinit var taskPageAdapter: TaskPageAdapter

    // 最新供应列表
    private lateinit var supplyAdapter: ProvideListAdapter

    // 最新需求列表
    private lateinit var needsAdapter: SupplierNeedsListAdapter

    override fun initIdentity(type: Int) {
        super.initIdentity(type)
        when (type) {
            IdentityType.OPERATING_UNIT.code -> {
                // 运营单位
                initPager()
                mBinding.lineLatest.visibility = View.GONE
            }
            IdentityType.BUILD_UNIT.code -> {
                // 施工单位
                initPager()
                mBinding.refreshLayout.setEnableLoadMore(true)
                // 获取最新供应列表
                mBinding.tvLatest.text = "最新供应"
                mViewModel.takePartSupplyList(mPage)
            }
            IdentityType.SUPPLIER.code -> {
                // 供应商
                mBinding.refreshLayout.setEnableLoadMore(true)
                // 获取最新需求列表
                mBinding.tvLatest.text = "最新需求"
                mViewModel.takePartNeedPage(mPage)

                //隐藏tab viewpager数据统计
                mBinding.tab.visibility=View.GONE
                mBinding.viewPager.visibility=View.GONE
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.image_message -> {
                RouteManager.Message.intentToMessageCenter(
                    mViewModel.mModel.getNoticeUnreadNum()
                )
            }
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        // 刷新获取网络数据
        mViewModel.getWorkBenchData()
        mPage = 1
        when (mViewModel.mModel.getIdentityType()) {
            IdentityType.BUILD_UNIT.code -> {
                // 获取最新供应列表
                mViewModel.takePartSupplyList(mPage)
            }
            IdentityType.SUPPLIER.code -> {
                // 获取最新需求列表
                mViewModel.takePartNeedPage(mPage)
            }
        }
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        when (mViewModel.mModel.getIdentityType()) {
            IdentityType.BUILD_UNIT.code -> {
                // 获取最新供应列表
                mViewModel.takePartSupplyList(mPage++)
            }
            IdentityType.SUPPLIER.code -> {
                // 获取最新需求列表
                mViewModel.takePartNeedPage(mPage++)
            }
        }
    }

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(this)

        // 设置状态栏字体颜色
        ImmersionBar.with(this)
            .fitsSystemWindows(true)
            .statusBarDarkFont(true)
            .init()

//        // 获取缓存数据
//        mViewModel.loadCacheData()
    }


    override fun initViewObservable() {
        super.initViewObservable()
        // 刷新监听
        observe(mViewModel.mUI.initRefreshEvent()) {
            mBinding.refreshLayout.finishRefresh(it!!)
        }

        // 加载监听
        observe(mViewModel.mUI.initLoadEvent()) {
            mBinding.refreshLayout.finishLoadMore(it!!)
        }

        // 初始化轮播图
        initBanner()
        // 初始化公告及消息数量
        initInformation()
        // 初始化常用应用
        initCommonApply()
        // 最新供应列表
        setProvideList()
        // 最新需求列表
        setNeedsList()
    }

    /**
     * 初始化ViewPager
     */
    private fun initPager() {
        if (mBinding.viewPager.adapter == null) {
            taskPageAdapter = TaskPageAdapter(
                mViewModel.getTaskTabsList(), childFragmentManager, lifecycle
            )
        }
        mBinding.viewPager.adapter = taskPageAdapter

        val ll = mBinding.tab.getChildAt(0) as LinearLayout
        ll.showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE
        ll.dividerDrawable =
            ContextCompat.getDrawable(requireActivity(), R.drawable.sp_tabs_vertical_divider)
        ll.dividerPadding = DisplayUtil.dp2px(requireContext(), 12)

        //绑定tabLayout和viewPager
        TabLayoutMediator(
            mBinding.tab, mBinding.viewPager,
            true, true
        ) { tab, position ->
            tab.text = mViewModel.getTaskTabsList()[position]
        }.attach()
    }

    /**
     * 初始轮播图
     */
    private fun initBanner() {
        observe(mViewModel.bannerListEvent) {
            if (!this::mBannerAdapter.isInitialized) {
                // 第一次加载
                mViewModel.mModel.saveCacheListData(it!!)
                mBannerAdapter = HomeBannerAdapter(it as MutableList<BannerVO>)
                mBinding.banner.setAdapter(mBannerAdapter)
            } else {
                mBannerAdapter.setDatas(it)
            }
        }
    }

    /**
     * 公告及消息数量
     */
    private fun initInformation() {

        observe(mViewModel.noticeQtyEvent) {
            if (it == 0) {
                mBinding.tvUnreadNum.visibility = View.GONE
            } else {
                mBinding.tvUnreadNum.visibility = View.VISIBLE
                mBinding.tvUnreadNum.text = "$it"
            }
        }

        observe(mViewModel.noticeListEvent) {
            if (it!!.isNotEmpty()) {
                mBinding.tvSwitcher.setAdapter(object : RollingTextAdapter() {
                    override fun getCount(): Int {
                        return it.size
                    }

                    override fun getView(
                        context: Context?,
                        contentView: View?,
                        position: Int,
                    ): View {
                        Logs.d("RollingTextAdapter $position")
                        val view = View.inflate(context, R.layout.view_item_rolling, null)
                        val binding: ViewItemRollingBinding? = DataBindingUtil.bind(view)
                        binding!!.tvContent.text = it[position].noticeTitle
                        return view
                    }
                })
                mBinding.tvSwitcher.startFlipping()
                mBinding.tvSwitcher.setOnItemClickListener { position:Int->
                    val info=it[position]
                    ARouter.getInstance().build(RoutePath.Message.MESSAGE_DETAIL)
                        .withString("title", info.noticeTitle)
                        .withString("content", info.noticeContent)
                        .withString("createTime", info.createTime)
                        .navigation()
                }
            }
        }
    }

    /**
     * 常用应用
     */
    private fun initCommonApply() {
        observe(mViewModel.commonApplyEvent) {
            mHomeApplyAdapter = HomeApplyAdapter(it!!, 4)
            mBinding.ultraViewpager.adapter = mHomeApplyAdapter
            mHomeApplyAdapter.setItemClickListener(object : HomeApplyAdapter.ItemClickListener {
                override fun onClickItem(position: Int, itemData: CommonApplyListVO) {
                    Logs.d("onClickItem $position ${itemData.name}")
                    (requireActivity() as Main2Activity).navigationIconUI(itemData)
                }
            })
            mBinding.indicator.attachToViewPager(mBinding.ultraViewpager.viewPager)
        }
    }

    /**
     * 最新供应列表
     */
    private fun setProvideList() {
        //  最新供应
        observe(mViewModel.provideListEvent) {
            if (it != null && it.records.isNotEmpty()) {
                if (!this::supplyAdapter.isInitialized) {
                    mBinding.rvList.layoutManager = LinearLayoutManager(
                        requireContext(), LinearLayoutManager.VERTICAL, false
                    )
                    supplyAdapter = ProvideListAdapter(it.records as MutableList<ReleaseSupplyVo>)
                    mBinding.rvList.adapter = supplyAdapter
                    supplyAdapter.setOnItemClickListener { adapter, view, position ->
                        val info = adapter.data[position] as ReleaseSupplyVo
                        RouteManager.Mine.intentToProvideDetail(info.id)
                    }
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(true)
                    if (mPage == 1) {
                        supplyAdapter.setNewInstance(it.records as MutableList<ReleaseSupplyVo>)
                    } else {
                        supplyAdapter.addData(it.records)
                    }
                }
                if (supplyAdapter.data.size == it.total) {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            } else {
                mBinding.lineLatest.visibility = View.GONE
                mBinding.refreshLayout.setEnableLoadMore(false)
            }
        }
    }

    /**
     * 最新需求列表
     */
    private fun setNeedsList() {
        observe(mViewModel.releaseSupplyListEvent) {
            if (it != null && it.records.isNotEmpty()) {
                if (!this::needsAdapter.isInitialized) {
                    mBinding.rvList.layoutManager = LinearLayoutManager(
                        requireContext(), LinearLayoutManager.VERTICAL, false
                    )
                    needsAdapter =
                        SupplierNeedsListAdapter(it.records as MutableList<ReleaseNeedsVO>)
                    mBinding.rvList.adapter = needsAdapter
                    needsAdapter.setOnItemClickListener { adapter, view, position ->
                        val info = adapter.data[position] as ReleaseNeedsVO
//                        RouteManager.Mine.intentToConstructionNeedsDetail(info.id)
                    }
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(true)
                    if (mPage == 1) {
                        needsAdapter.setNewInstance(it.records as MutableList<ReleaseNeedsVO>)
                    } else {
                        needsAdapter.addData(it.records)
                    }
                }
                if (needsAdapter.data.size == it.total) {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            } else {
                mBinding.lineLatest.visibility = View.GONE
                mBinding.refreshLayout.setEnableLoadMore(false)
            }
        }
    }
}